package com.simpd.activity;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpResponseException;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import cn.pedant.SweetAlert.SweetAlertDialog;

import com.another.helper.InstallAPK;
import com.another.helper.Logger;
import com.example.simpd.R;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.simpd.db_helper.DatabaseHelper;
import com.simpd.http_helper.CustomHttpClient;
import com.simpd.model.ServerSimpd;
import com.simpd.model.SessionSimpd;
import com.simpd.model.SynchronizeConstant;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	EditText username; 
	EditText password; 
	TextView textResult; 
	Button btnLogin;
	Button btnDrop;
	RelativeLayout loadingSection; 
	FloatingActionButton btnSetting;
	
	private String result = null;
	private String errorMessage;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ActionBar actionBar = getActionBar(); 
		actionBar.hide();
		
		DatabaseHelper db = new DatabaseHelper(this);
		if(db.getWritableDatabase().getVersion() != DatabaseHelper.VERSION){
			db.onUpgrade(db.getWritableDatabase(),db.getWritableDatabase().getVersion() , DatabaseHelper.VERSION);
			Log.d("upgrade database", "upgrade database from version : "+db.getWritableDatabase().getVersion()+"" +
					" to version : "+DatabaseHelper.VERSION);
		}
		
		SessionSimpd session =  db.getSession();
		// Log.d("[session]", session.toString());
		if(session != null && !(session.getToken().equalsIgnoreCase("logout"))){
			Log.d("[session-exist]", "token is empty? "+(session.getToken().equalsIgnoreCase("logout")));
			
			Intent intent = new Intent(MainActivity.this, HomeActivity.class); 
			startActivity(intent);
			finish();
		}
		
		Log.d("[session-null]", "there is no session");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_login);
		
		
		username = (EditText) findViewById(R.id.flat_login_input_username);
		password = (EditText) findViewById(R.id.flat_login_input_password);
		
		textResult		= (TextView) findViewById(R.id.flat_login_text_result); 
		btnLogin 	 	= (Button) findViewById(R.id.flat_login_button_login); 
		btnDrop			= (Button) findViewById(R.id.flat_login_button_drop);
		loadingSection  = (RelativeLayout) findViewById(R.id.flat_login_loading_group);
		
		btnSetting = (FloatingActionButton) findViewById(R.id.flat_login_button_setting); 
		
		
		// String unipValue = this.getString(R.string.unip_value);
		// String utokValue = this.getString(R.string.utok_value);
		username.setText("");
		if(session!=null && (session.getUnip() != null || session.getUnip() !="" )){
			username.setText(session.getUnip());
		}
		username.setSelection(username.getText().toString().length());
		password.setText("");
		
		btnDrop.setVisibility(View.GONE);
		textResult.setVisibility(View.GONE);
		
		btnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				processLogin(v);	
				
			}
		});
		
		btnSetting.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, SettingActivity.class);
				startActivity(intent);
			}
		});
		
		btnDrop.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//updateApk(v);
				Intent intent = new Intent(MainActivity.this, ExampleActivity.class);
				startActivity(intent);
			}
		});
	}
	
	private void updateApk(View v){
		Intent intent; 
		PackageManager manager = getPackageManager(); 
		try {
			intent = manager.getLaunchIntentForPackage("com.nusaraya.simpd"); 
			if(intent == null){
				throw new PackageManager.NameNotFoundException(); 
			}
			intent.addCategory(Intent.CATEGORY_LAUNCHER); 
			startActivity(intent); 
		} catch (PackageManager.NameNotFoundException e) {
			SweetAlertDialog dialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.PROGRESS_TYPE);
			dialog.setTitleText("updating apps...");
			dialog.setCancelable(false);
			
			SweetAlertDialog errorDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE); 
			InstallAPK downloadAndInstall = new InstallAPK(MainActivity.this, dialog); 
			downloadAndInstall.setErrorDialog(errorDialog);
			downloadAndInstall.execute("http://192.168.1.148/android/SimPdSvn.apk");
		}
	}
	
	private void dropTable(View v){
		DatabaseHelper db = new DatabaseHelper(getApplicationContext());
		db.dropTable();
		Toast.makeText(getApplicationContext(), "table dropped", Toast.LENGTH_SHORT).show();
	}
	
	
	public void processLogin(View view){
		if(password.getText().toString().equalsIgnoreCase("") 
		   || username.getText().toString().equalsIgnoreCase("")){
			SweetAlertDialog alert = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE); 
			alert.setTitleText("Oops..!!"); 
			alert.setContentText("Username atau password tidak boleh kosong!");
			alert.show();
		}else{
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("unip", username.getText().toString());
			params.put("utok", password.getText().toString());
			
			DatabaseHelper db  = new DatabaseHelper(MainActivity.this); 
			ServerSimpd server =  db.getServer();
			String url ="";
			if(server == null){
				server = new ServerSimpd();
				server.setServerUrl(SynchronizeConstant.DEFAULT_SERVER_SIMPD);
				db.insertServer(server);
			}
			url = server.getServerUrl()+"/site/loginMobile";
			Thread thread = new Thread(new LoginThread(url, params));
			thread.start();
			
		}
		
	}
	
	public boolean loginUsingThreads(String url, HashMap<String, String> params){
		boolean successful = false;
		
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("unip", params.get("unip")));
		postParameters.add(new BasicNameValuePair("utok", params.get("utok")));
		
		// String url = "http://sppd.gorontaloprov.go.id/simpd/site/loginMobile";
		Log.d("[post-url]", "post url : "+url); 
		Log.d("[post-params]", "unip : "+postParameters.get(0).getValue()+", utok : "+postParameters.get(1).getValue());
		String response = null; 
		String res 		= null;
		try {
			errorMessage = null;
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			
			Log.d("[post-request]", "perform post request");
			res = response.toString(); 

			/*res = res.replaceAll("\\s+", "");*/

			Log.d("[post-result]", "post result: "+res);
			
			Log.d("[request-result]", "request result : "+res);
			if(res != null){
				JSONParser jsonParse  = new JSONParser(); 
				JSONObject jsonObject;
				try {
					jsonObject = (JSONObject) jsonParse.parse(res);
					// get a String from the JSON Object
					result = (String) jsonObject.get("token");
					if(result != null){
						DatabaseHelper db = new DatabaseHelper(MainActivity.this); 
						SessionSimpd session = db.getSession();
						if(session == null){
							session = new SessionSimpd();
							session.setUnip(username.getText().toString()); 
							session.setToken(result);
							db.insertSession(session);
							Log.d("[insert-session]", session.toString());
						}else{
							session.setUnip(username.getText().toString());
							session.setToken(result);
							db.updateSession(session);
							Log.d("[update-session]", session.toString());
						}
						
						successful = true;
					}
				} catch (ParseException e) {
					e.printStackTrace();
					Logger.e(MainActivity.this, "Login error", "Json Parse error because return " +
							"value from server wrong! Response server: \n"+res+"\n Exception message : "+ e.toString());
				} 
			}
						
		} catch (HttpResponseException e) {
			Log.d("[HttpResponseException]", "request error cause : "+e);
			errorMessage = "respond dari server tidak sesuai format yang ditentukan!!";
			Logger.e(MainActivity.this, "login error", e.toString());
		}catch (HttpException e) {
			Log.d("[HttpException]", "request error cause : "+e.toString());
			errorMessage = "error ketika mengakses server!";
			Logger.e(MainActivity.this, "login error", e.toString());
		}catch (UnknownHostException e) {
			Log.d("[UnknownHostException]", "request error cause : "+e.toString());
			errorMessage = "alamat server tidak bisa diakses, pastikan Anda terkoneksi dengan internet dan cobalah beberapa saat lagi!";
			Logger.e(MainActivity.this, "login error", e.toString());
		}catch (SocketException e) {
			Log.d("[SocketException]", "request error cause : "+e.toString());
			errorMessage = "alamat server untuk login tidak dapat diakses, pastikan server tidak dalam keadaan down!";
			Logger.e(MainActivity.this, "login error", e.toString());
		}
		
		catch (Exception e) {
			Log.d("[Exception]", "request error cause : "+e);
			errorMessage = e.getMessage();
			if(errorMessage ==null || errorMessage.equalsIgnoreCase("null")){
				errorMessage = "Username atau password yang Anda masukkan salah!";
			}else{
				errorMessage = "tidak bisa terhubung dengan server! Silahkan periksa koneksi internet Anda!";
			}
			Logger.e(MainActivity.this, "login error", e.toString());
		}finally{
			
			MainActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					Log.d("[result and errorMessage]", "result : "+result+", errorMessage : "+errorMessage);
					if(result != null && errorMessage == null){
						Log.d("[if login true]", "result : "+result+", errorMessage : "+errorMessage);
						
						textResult.setText("username and password correct !"); 
						// textResult.setTextColor(Color.GREEN);
						Intent intent = new Intent(MainActivity.this, HomeActivity.class);
						startActivity(intent);
						finish();
					}else{
						Log.d("[if login false]", "result : "+result+", errorMessage : "+errorMessage);
						
						SweetAlertDialog alert = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE);
						alert.setTitleText("Opps...!");
						if(errorMessage ==null || errorMessage.equalsIgnoreCase("null")){
							errorMessage = "Username atau password yang Anda masukkan salah!";
						}
						alert.setContentText("Terjadi kesalahan karena : "+errorMessage);
						alert.show();
						textResult.setText("Login gagal karena : "+errorMessage); 
						// textResult.setTextColor(Color.RED);
					}
					loadingSection.setVisibility(View.GONE);
					textResult.setVisibility(View.VISIBLE);
				}
			});
			
		}

		return successful;
	}
	
	private class LoginThread implements Runnable{
		private String url; 
		private HashMap<String, String> params;
		
		public LoginThread(String url, HashMap<String, String> params){
			this.url	= url;
			this.params = params;
		}
		@Override
		public void run() {
			MainActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					loadingSection.setVisibility(View.VISIBLE);
					textResult.setVisibility(View.GONE);
				}
			});
			loginUsingThreads(url, params);
		}
		
	}

	
		
	
}
